package work.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.bean.BookwareAndUser;
import work.bean.BorrowGrade;
import work.bean.FindReaderHistory;
import work.bean.ReaderHistory;
import work.entity.Book;
import work.entity.Bookware;
import work.entity.Borrow;
import work.service.BookService;
import work.service.BookwareService;
import work.service.BorrowService;
import work.vo.DataVo;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/bookware")
public class BookwareHandler {

    @Autowired
    private BookwareService bookwareService;
    @Autowired
    private BookService bookService;
    @Autowired
    private BorrowService borrowService;

    // 读者图书模糊查询
    // 传入一个库存对象，元素可以全部为空，也可以全部都有
    @PostMapping("/findbookware")
    public DataVo findBookware(@RequestBody Bookware bookware1) {
        DataVo dataVo = new DataVo();
        if (bookware1.getBookWareId().length() > 11) {
            bookware1.setBookWareId(bookware1.getBookWareId().substring(0, 11));
        }
        List<Bookware> list = bookwareService.findByBookware1(bookware1);
        if (list.isEmpty()) {
            dataVo.setCode(130);
            dataVo.setMsg("该图书不存在");
        } else {
            dataVo.setCode(131);
            dataVo.setMsg("查询图书成功");
            dataVo.setData(list);
        }
        return dataVo;
    }

    // 预约图书2，更改后
    // 传入一个bookwareAndUser对象
    // 先更改bookware表lending，再插入borrow表，后更改book表status
    @PostMapping("/order")
    public DataVo orderBook(@RequestBody BookwareAndUser bookwareAndUser) throws ParseException {
        DataVo dataVo = new DataVo();
        Book book = new Book();
        // 根据传入的库存编号查找一个对象，存在则说明该书存在
        Bookware bookware = bookwareService.findById(bookwareAndUser.getBookWareId());
        if (bookware.getBookTotal() - bookware.getBookLending() == 0) {
            dataVo.setCode(140);
            dataVo.setMsg("没有可以预约的图书");
            return dataVo;
        }
        // 更新lending
        bookware.setBookLending(bookware.getBookLending() + 1);
        int a = bookwareService.updateWare(bookware);
        // 更新数据库
        // 更新borrow，按照borrowId, bookId, userId, borrowDate, shouldDate,borrowStatus顺序更新
        Borrow borrow = new Borrow();
        borrow.setBorrowId(String.valueOf(System.currentTimeMillis()));
        // 13位的时间戳
        borrow.setBookId(bookService.selectBookIdByBookWareId(bookware.getBookWareId())); // 根据库存编号找出可以外借的书本编号
        borrow.setUserId(bookwareAndUser.getUserId());
        // 根据传入的用户编号设置
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MMdd");
        Date now = new Date();
        borrow.setBorrowDate(simpleDateFormat.parse(simpleDateFormat.format(now))); // 设置符合格式的借书日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MONTH, 1);
        borrow.setShouldDate(calendar.getTime());
        // 设置应还日期，即在借书日期基础上加上一个月
        borrow.setBorrowStatus("预约");
        // 设置借阅状态
        int b = borrowService.insertBorrow(borrow);
        // 更新数据库
        // 更新status
        book.setBookId(borrow.getBookId());
        // 设置该书对应的状态为“外借”
        book.setBookStatus("外借");
        // 更新数据库
        int c = bookService.updatebookStatus1(book);
        if (a == 0 || b == 0 || c == 0) {
            dataVo.setCode(141);
            dataVo.setMsg("预约失败");
        } else {
            dataVo.setCode(142);
            dataVo.setMsg("预约成功");
        }
        return dataVo;
    }


    // 图书评分2，修改后
    // 参考商业网站的评分规则再结合本系统的特点，评分规则如下：分数 = （该用户输入的分数 + （200 + 历史借阅） * 原分数）/ （200 + 历史借阅）
    // 传入borrowGrade对象
    @PostMapping("/grade")
    public DataVo gradeBook( @RequestBody BorrowGrade borrowGrade) {
        DataVo dataVo = new DataVo();
        Double grade = borrowGrade.getGrade();
        if (grade > 10 || grade < 0) {
            dataVo.setCode(160);
            dataVo.setMsg("输入分数不合要求");
            return dataVo;
        }
        // 获取该借阅记录对应的图书id后切割成库存id，再获取一个库存对象进行评分更新
        String s = borrowGrade.getBookId().substring(0, 11);
        Bookware bookware = bookwareService.findById(s);
        Double b = (grade + (200 + bookware.getBookHistory()) * bookware.getBookGrade()) / (200 + bookware.getBookHistory());
        BigDecimal bg = new BigDecimal(b);
        b = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); //化为两位小数的形式
        bookware.setBookGrade(b);
        bookwareService.updateWare(bookware);
        dataVo.setCode(161);
        dataVo.setMsg("评分成功");
        return dataVo;
    }

    // 查看用户借阅历史2，修改后
    @PostMapping("/findReaderHistory")
    public DataVo findReaderHistory(@RequestBody FindReaderHistory findReaderHistory) {
        DataVo dataVo = new DataVo();
        Bookware bookware = new Bookware();
        bookware.setBookName(findReaderHistory.getBookName());
        bookware.setBookAuthor(findReaderHistory.getBookAuthor());
        bookware.setBookPublisher(findReaderHistory.getBookPublisher());

        bookware.setBookType(findReaderHistory.getBookType());
        List<Borrow> borrows = borrowService.selectByUser(findReaderHistory.getUserId());
        List<Bookware> bookwares = new ArrayList<>();
        if (borrows.isEmpty()) {
            dataVo.setCode(170);
            dataVo.setMsg("该用户没借阅记录");
            return dataVo;
        }
        for (Borrow borrow: borrows) {
            bookware.setBookWareId(borrow.getBookId().substring(0, 11));
            List<Bookware> bookwares1 = bookwareService.findByBookware1(bookware);
            bookwares.remove(bookwares1);
            bookwares.addAll(bookwares1);
        }
        ReaderHistory readerHistory = new ReaderHistory();
        dataVo.setCode(171);
        dataVo.setMsg("查询成功");
        dataVo.setData(readerHistory.getReaderHistory(borrows, bookwares));
        return dataVo;
    }

    // 读者查看系统高分图书
    @PostMapping("/findTopGrade")
    public DataVo findTopGrade() {
        DataVo dataVo = new DataVo();

        List<Bookware> bookwares = bookwareService.orderByGrade();
        if (bookwares.isEmpty()) {
            dataVo.setCode(190);
            dataVo.setMsg("查询失败");
        } else {
            dataVo.setCode(190);
            dataVo.setMsg("查询成功");
            dataVo.setData(bookwares);
        }
        return dataVo;
    }

    // 工作人员查看系统图书评分
    // 与读者查看系统高分图书差异在于：工作人员可以查看250本，而且可以是升序也可以是降序
    // 前端传入一个int型sort参数，0表示升序，1表示降序
    @PostMapping("/findGrade")
    public DataVo findGrade(@RequestBody int sort) {
        DataVo dataVo = new DataVo();

        List<Bookware> bookwareList;
        if (sort == 1) {
            bookwareList = bookwareService.orderByGradeDesc();
        } else {
            bookwareList = bookwareService.orderByGradeAsc();
        }

        if (bookwareList.isEmpty()) {
            dataVo.setCode(320);
            dataVo.setMsg("查询失败");
        } else {
            dataVo.setCode(321);
            dataVo.setMsg("查询成功");
            dataVo.setData(bookwareList);
        }

        return dataVo;
    }

    // 工作人员查看图书统计信息
    @PostMapping("/BookwareStatistics")
    public DataVo BookwareStatistics() {
        DataVo dataVo = new DataVo();

        List<Bookware> bookwares = bookwareService.findAll();

        if (bookwares.isEmpty()) {
            dataVo.setCode(310);
            dataVo.setMsg("查询所有书籍失败");
            return dataVo;
        }

        dataVo.setCode(311);
        dataVo.setMsg("查询所有书籍成功");
        dataVo.setData(bookwares);
        return dataVo;
    }
}